package org.singledog.form.builder.dataset;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.singledog.form.builder.util.HttpClientUtil;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author adam
 * @date 2019/4/30
 */
@Slf4j
public class HttpDataSet extends AbstractDataSet {

	@Override
	public DataSetType supportDataSetType() {
		return DataSetType.HTTP;
	}

	@Override
	public Object queryData(String datasetCode, Map<String, Object> params) {
		DataSetMeta meta = getDataSetMeta(datasetCode);

		Assert.notNull(meta.getUrl(), "dataset url can not be null !");
		String method = null;
		if (StringUtils.isEmpty(meta.getMethod())) {
			method = "GET";
		} else {
			method = meta.getMethod().toUpperCase();
		}

		String ret = null;
		try {
			switch (method) {
				case "GET":
					ret = HttpClientUtil.doGet(meta.getUrl(), params);
					break;
				case "POST":
					ret = HttpClientUtil.doPost(meta.getUrl(), params);
					break;
				default:
					ret = null;
			}
		} catch (Exception e) {
			log.error("HttpDataSet:Error request url : {}, params: {}", meta.getUrl(), JSON.toJSONString(params));
			log.error(e.getMessage(), e);
		}

		if (StringUtils.isEmpty(ret)) {
			return null;
		}

		try {
			return JSON.parseObject(ret);
		} catch (Exception e) {
			return JSON.parseArray(ret);
		}
	}
}
